package com.example.lib_common.livedata_eventbus

import androidx.lifecycle.MutableLiveData

/*
这个livedata没测试，也是为了解决数据倒灌的问题
 */
object LiveEventBus {
    private val events = mutableMapOf<String, MutableLiveData<Event<*>>>()

    @Synchronized
    fun <T> with(key: String, type: Class<T>): MutableLiveData<Event<T>> {
        if (!events.containsKey(key)) {
            events[key] = MutableLiveData()
        }
        @Suppress("UNCHECKED_CAST")
        return events[key] as MutableLiveData<Event<T>>
    }

    fun <T : Any> postEvent(key: String, value: T) {
        with(key, Any::class.java).postValue(Event(value))

    }

    class Event<T>(private val content: T) {
        private var hasBeenHandled = false

        fun getContentIfNotHandled(): T? {
            return if (hasBeenHandled) {
                null
            } else {
                hasBeenHandled = true
                content
            }
        }

        fun peekContent(): T = content
    }
}
